package android.test;

import android.app.Activity;
import android.os.Bundle;
import android.image.*;
import android.view.Display;
import android.view.Window;
import android.view.WindowManager;
import android.world.VoidWorld;
import java.text.DecimalFormat;

public class BounceDown extends Activity{
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        Display dis = getWindowManager().getDefaultDisplay();
        new Bounce(dis.getWidth(), dis.getHeight()).bigBangLandscapeFullscreen(this);
    }
}
class Ball{
    double x, y, vx, vy;

    Ball(double x, double y, double vx, double vy){
        this.x = x;
        this.y = y;
        this.vx = vx;
        this.vy = vy;
    }
    
    void move(){
        this.x += this.vx;
        this.y -= this.vy;
    }
    
    void gravity(double dx, double dy){
        this.vx += dx;
        this.vy += dy;
    }
    
    void bounce(int w, int h){
        if(x+this.vx < 15 || x+this.vx > w-15){
            if(x+this.vx < 15)x = 15;
            else x = w-15;
            this.vx *= -0.8;
        }
        if(y-this.vy < 15 || y-this.vy > h-15){
            if(y-this.vy < 15)y = 15;
            else y = h-15;
            this.vy *= -0.8;
        }
    }
    
    Scene draw(Scene scn){
        return scn.placeImage(new Circle(15, "solid", "blue")
                              .overlay(new Circle(15, "solid", "blue")), this.x, this.y)
                  /*.placeImage(new Text("("+Bounce.format.format(x)+", "+
                                       Bounce.format.format(y)+", "+
                                       Bounce.format.format(vx)+", "+
                                       Bounce.format.format(vy)+")", 15, "black"),
                        this.x, this.y+10)*/;
    }
}

class Bounce extends VoidWorld{
    int WIDTH, HEIGHT;
    double ang;
    double mag;
    
    Ball ball;
    
    Bounce(int w, int h){
        this.WIDTH = w;
        this.HEIGHT = h;
        this.ang = 0;
        this.mag = 0;
        this.ball = new Ball(w/2, h/2, 0, 0);
    }
    
    public void onOrientation(double x, double y, double z){
        double ang = Math.acos(x/Math.sqrt(x*x + y*y))+Math.PI;
        if(y < 0)this.ang = 2*Math.PI-ang;
        else this.ang = ang;
        this.mag = Math.sqrt(x*x + y*y)*0.2;
    }

    public void onTick(){
        this.ball.bounce(WIDTH, HEIGHT);
        this.ball.move();
        this.ball.gravity(this.mag*Math.cos(this.ang), 
                          this.mag*Math.sin(this.ang));
    }
    
    static DecimalFormat format = new DecimalFormat("0.00"); 
    public Scene onDraw(){
        return this.ball.draw(new EmptyScene(WIDTH, HEIGHT))
            .placeImage(new Text("Ang: "+format.format(this.ang*180/Math.PI)+
                                 "  Mag: "+format.format(this.mag), 20, "black"),
                        WIDTH/2, 40);
    }
}